#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "get_temp.h"
	
#define PATH "/sys/bus/w1/devices/"

#define  HOST        "localhost"
#define  PORT        1884
#define  KEEP_LIVE   60
#define  topic       "temp"
/*
struct rpi_data_s
{
	char   ID[12];
	float  temp;
};

int get_temperature(struct rpi_data_s  *rpi_data);

int main (int argc,char ** argv)
{
        int                     rv=-1;
	struct                  rpi_data_s  rpi_data;


	memset(&rpi_data, 0, sizeof(rpi_data));

	rv = get_temperature(&rpi_data);
	if(rv<0)
	{
		printf("get temperature failure,return value:%d\n",rv);
		return -3;
	}
	printf("temp:%f\n",rpi_data.temp);
			
}
*/
int get_temperature(struct rpi_data_s  *rpi_data)
{
	int 		        fd=-1;
	char 		        buf[128];
	char	       	       *str=NULL;
	DIR	               *dirp=NULL;	
	struct dirent          *dirrep=NULL;
	int			found=0;
	char			w1_path[128]=PATH;

	dirp = opendir(PATH);
		if(!dirp)
	{
		printf("dir %s : %s",PATH,strerror(errno));
		return -1;
	}

	while(NULL != (dirrep = readdir(dirp)))
	{
		if(strstr(dirrep->d_name,"28-"))
		{	
			found = 1;
			strncat(w1_path,dirrep->d_name,sizeof(w1_path)-strlen(w1_path));
			strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));
		}
	}
	closedir(dirp);
	
	memset(buf,0,sizeof(buf));
	fd = open(w1_path,O_RDONLY);
	if (!fd)
	{
		perror("FILE problem");
		return -2;
	}
	read(fd,buf,sizeof(buf));
	
	str=strstr(buf,"t=");
	if(!str)
	{
		printf("can't not find string\n");
		return -3;
	}
	str += 2;
	rpi_data->temp	= atof(str)/1000;
	
	close(fd);
	return 0;
}

